package com.itheima.interc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginCheck implements HandlerInterceptor {

    //在访问指定路径前先处理拦截逻辑
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截器拦截到{}",requestURI);
        if(request.getSession().getAttribute("employee")!=null){
            log.info("登录成功，用户id是：{}",request.getSession().getAttribute("employee"));
            return true;
        }
        log.info("用户未登录");
        R result=R.error("NOTLOGIN");
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
        return false;
    }
}
